<?php

namespace Org\SueCrypt;

/**
 * SueRandom 类
 *
 * @since VER:1.0; DATE:2016-4-26; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
 */
class SueRandom {

    /**
     * 随机加密算法
     * @param string $data
     * @param string $key
     * @return string
     * @since 1.0 <2014-10-15> SoChishun Added.
     * @since 2.0 <2016-4-26> SoChishun 拆分并改为规范化为静态方法.
     * @example
     *  $encode = encrypt_rnd("测试内容abc123!@#", 'ENCRYPT', '123');
     *  echo "加密结果：" . $encode; // CewAtwqAAulV+AufAuQChlDUAedQ/FfvVzVQMFEzBzUAMAMxV3UDQQUn,随机变化
     *  $decode = encrypt_rnd($encode, 'DENCRYPT', '123');
     *  echo "<br />解密结果：" . $decode; // 测试内容abc123!@#
     */
    public static function encrypt($data, $key = 'sue123!@#') {
        srand((double) microtime() * 1000000);
        $rand = rand(1, 10000);
        $encrypt_key = md5($rand);
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($data); $i++) {
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            $tmp .= $encrypt_key[$ctr] . ($data[$i] ^ $encrypt_key[$ctr++]);
        }
        $tmp = self::encrypt_rnd_key($tmp, $key);
        return base64_encode($tmp);
    }

    /**
     * 解密
     * @param type $data
     * @param type $mode
     * @param type $key
     * @return type
     * @since 1.0 2016-4-26 SoChishun Added.
     */
    public static function decrypt($data, $key = 'sue123!@#') {
        $txt = base64_decode($data);
        $txt = self::encrypt_rnd_key($txt, $key);
        $tmp = '';
        for ($i = 0; $i < strlen($txt); $i++) {
            $md5 = $txt[$i];
            $tmp .= $txt[++$i] ^ $md5;
        }
        return $tmp;
    }

    /**
     * encrypt_rnd()辅助函数
     * @param $data 字符串
     * @param $encrypt_key 密匙
     * @return string 加密后的字符串
     * @since 1.0 <2014-10-15> SoChishun Added.
     */
    private static function encrypt_rnd_key($data, $key) {
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($data); $i++) {
            $ctr = $ctr == strlen($key) ? 0 : $ctr;
            $tmp .= $data[$i] ^ $key[$ctr++];
        }
        return $tmp;
    }

}
